package com.itjin.health.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itjin.health.common.BaseResponse;
import com.itjin.health.common.ResultUtils;
import com.itjin.health.domain.dto.QrCodeRequest;
import com.itjin.health.domain.entity.GroupChatQrCode;
import com.itjin.health.domain.vo.QrCodeVO;
import com.itjin.health.exception.BusinessException;
import com.itjin.health.exception.ErrorCode;
import com.itjin.health.service.GroupChatQrCodeService;
import com.itjin.health.service.impl.GroupChatQrCodeServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/system")
@Api(tags = "系统管理接口")
@Slf4j
public class SystemController {

  @Resource
  private GroupChatQrCodeService groupChatQrCodeService;

  @Resource
  private GroupChatQrCodeServiceImpl groupChatQrCodeServiceImpl;

  /**
   * 上传群聊二维码（管理员/教师）
   *
   * @param qrCodeImage 二维码图片
   * @param expiryTime  过期时间（可选）
   * @param status      状态（可选，默认Active）
   * @param request     HTTP请求
   * @return 上传后的二维码信息
   */
  @PostMapping("/qrcode/upload")
  @ApiOperation(value = "上传群聊二维码")
  public BaseResponse<QrCodeVO> uploadQrCode(
      @RequestParam("qrCodeImage") @ApiParam("二维码图片") MultipartFile qrCodeImage,
      @RequestParam(value = "expiryTime", required = false) @ApiParam("过期时间") String expiryTime,
      @RequestParam(value = "status", required = false) @ApiParam("状态") String status,
      HttpServletRequest request) {
    // 从Session中获取用户ID
    Integer userId = (Integer) request.getSession().getAttribute("userId");
    if (userId == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }

    // 上传二维码
    GroupChatQrCode qrCode = groupChatQrCodeService.uploadQrCode(qrCodeImage, expiryTime, status, userId);
    QrCodeVO qrCodeVO = groupChatQrCodeServiceImpl.getQrCodeVO(qrCode);
    return ResultUtils.success(qrCodeVO);
  }

  /**
   * 更新群聊二维码（管理员/教师）
   *
   * @param qrCodeId    二维码ID
   * @param qrCodeImage 二维码图片（可选）
   * @param expiryTime  过期时间（可选）
   * @param status      状态（可选）
   * @param request     HTTP请求
   * @return 更新结果
   */
  @PutMapping("/qrcode/update")
  @ApiOperation(value = "更新群聊二维码")
  public BaseResponse<Boolean> updateQrCode(
      @RequestParam("qrCodeId") @ApiParam("二维码ID") Integer qrCodeId,
      @RequestParam(value = "qrCodeImage", required = false) @ApiParam("二维码图片") MultipartFile qrCodeImage,
      @RequestParam(value = "expiryTime", required = false) @ApiParam("过期时间") String expiryTime,
      @RequestParam(value = "status", required = false) @ApiParam("状态") String status,
      HttpServletRequest request) {
    // 从Session中获取用户ID
    Integer userId = (Integer) request.getSession().getAttribute("userId");
    if (userId == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }

    // 构建更新请求
    QrCodeRequest qrCodeRequest = new QrCodeRequest();
    qrCodeRequest.setQrCodeId(qrCodeId);
    qrCodeRequest.setQrCodeImage(qrCodeImage);
    if (expiryTime != null && !expiryTime.isEmpty()) {
      qrCodeRequest.setExpiryTime(java.time.LocalDateTime.parse(expiryTime));
    }
    qrCodeRequest.setStatus(status);

    // 更新二维码
    boolean result = groupChatQrCodeService.updateQrCode(qrCodeRequest, userId);
    return ResultUtils.success(result);
  }

  /**
   * 删除群聊二维码（管理员/教师）
   *
   * @param qrCodeId 二维码ID
   * @param request  HTTP请求
   * @return 删除结果
   */
  @DeleteMapping("/qrcode/{qrCodeId}")
  @ApiOperation(value = "删除群聊二维码")
  public BaseResponse<Boolean> deleteQrCode(
      @PathVariable("qrCodeId") Integer qrCodeId,
      HttpServletRequest request) {
    // 从Session中获取用户ID
    Integer userId = (Integer) request.getSession().getAttribute("userId");
    if (userId == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }

    // 删除二维码
    boolean result = groupChatQrCodeService.deleteQrCode(qrCodeId, userId);
    return ResultUtils.success(result);
  }

  /**
   * 获取群聊二维码详情
   *
   * @param qrCodeId 二维码ID
   * @return 二维码详情
   */
  @GetMapping("/qrcode/{qrCodeId}")
  @ApiOperation(value = "获取群聊二维码详情")
  public BaseResponse<QrCodeVO> getQrCode(@PathVariable("qrCodeId") Integer qrCodeId) {
    // 获取二维码详情
    GroupChatQrCode qrCode = groupChatQrCodeService.getQrCode(qrCodeId);
    QrCodeVO qrCodeVO = groupChatQrCodeServiceImpl.getQrCodeVO(qrCode);
    return ResultUtils.success(qrCodeVO);
  }

  /**
   * 分页获取群聊二维码列表（管理员/教师）
   *
   * @param current 当前页
   * @param size    每页大小
   * @param status  状态筛选（可选）
   * @param request HTTP请求
   * @return 二维码列表
   */
  @GetMapping("/qrcode/list")
  @ApiOperation(value = "分页获取群聊二维码列表")
  public BaseResponse<Page<QrCodeVO>> listQrCodes(
      @RequestParam(defaultValue = "1") @ApiParam("当前页") long current,
      @RequestParam(defaultValue = "10") @ApiParam("每页大小") long size,
      @RequestParam(required = false) @ApiParam("状态") String status,
      HttpServletRequest request) {
    // 从Session中获取用户ID
    Integer userId = (Integer) request.getSession().getAttribute("userId");
    if (userId == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }

    // 分页获取二维码列表
    Page<GroupChatQrCode> qrCodePage = groupChatQrCodeService.listQrCodes(current, size, status);

    // 转换为VO
    Page<QrCodeVO> voPage = new Page<>(qrCodePage.getCurrent(), qrCodePage.getSize(), qrCodePage.getTotal());
    List<QrCodeVO> voList = groupChatQrCodeServiceImpl.getQrCodeVOList(qrCodePage.getRecords());
    voPage.setRecords(voList);

    return ResultUtils.success(voPage);
  }

  /**
   * 获取最新有效的群聊二维码（所有用户可访问）
   *
   * @return 最新有效的二维码
   */
  @GetMapping("/qrcode/latest")
  @ApiOperation(value = "获取最新有效的群聊二维码")
  public BaseResponse<QrCodeVO> getLatestQrCode() {
    // 获取最新有效的二维码
    GroupChatQrCode qrCode = groupChatQrCodeService.getLatestActiveQrCode();
    if (qrCode == null) {
      throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "没有可用的群聊二维码");
    }
    QrCodeVO qrCodeVO = groupChatQrCodeServiceImpl.getQrCodeVO(qrCode);
    return ResultUtils.success(qrCodeVO);
  }
}
